<template>
  <div class="cart pages" style="background-color: #F7F7FA">
      
      <!-- 

        <div class="mallcart-title flex f16" v-if="!show_all_choise" style="background-color: #fff;">
          <div class="sub"></div>
          <div class="write" @click="showDeleteChoice" style="background-color:#fff;color:#000">完成</div>
        </div>
        <div class="mallcart-title flex f16" v-if="show_all_choise && carts.items.length > 0" style="background-color:#fff;">
          <div class="sub"></div>
          <div class="write" @click="showAllChoice" style="color:#000">
            编辑
          </div>
        </div>

       -->

     <!--  <van-nav-bar
        title="岭南千果园"
        left-text="返回"
        :right-text=text
        left-arrow
        @click-right="showEdit"
        @click-left="back"
      />
   -->
      

    <van-checkbox-group v-model="selected_shop" @change="single_checkboxChange" class='out-group'>
        <div v-for="(shop,shopindex) in carts.items" :key="shopindex">
          <div class="container-cart">
            <div class="container-cart-shop flex-y center-layout" v-if="shop.shop">
              <!-- 循环店铺 -->
              <van-checkbox :name="shop.shop.id"></van-checkbox>
              <img class="cart-shop-cover" :src="shop.shop.cover"></img>
              <div class="flex1 flex-y" style="color: #222; font-size: 14px; letter-spacing: 1px" @click="showShop(shop.shop.id)">
                {{shop.shop.name}}
                <Icon type="ios-arrow-right" class='icon'></Icon>
              </div>
            </div>
            <van-checkbox-group v-model="this_check_val" @change="product_change" class='inner-group'>
              <!-- :disabled="item.stock ==0 &&  show_all_choise?'disable':''" -->
              <div class="cart-item flex-y " v-for="(item,pk) in shop.products" :key="item.id">
                <label class="radio flex center-layout">
                  <!--  hidden="{{!show_delete}}" -->
                  <van-checkbox :name="item.id" v-model="item.is_checked" style="flex: 1"></van-checkbox>
                </label>
                <div class="flex">
                  <img :src="item.cover" class="cart-img mr10 ml5" @click="showProduct(item.product_id)"></img>
                  <div class="cart-info sub flex-column">
                    <!-- v-if="show_all_choise" -->
                    <a class="flex mb5" style="align-items:center; " @click="showProduct(item.product_id)">
                      <div class="cart-title linediv2 flex1">{{item.name}}</div>
                    </a>
                    <div class="price">
                      <span class="#ad0e11">￥{{item.true_price}}</span>
                      <span style="">×{{item.num}}</span>
                    </div>
                    <div style="float:right; margin-right:10rpx; color:#ad0e11;">{{item.stock==0?'库存不足': (item.stock
                      < 5? '库存紧张': '')}} </div>
                        <div class="sub" v-if="!show_all_choise || current_finsh == item.id ">
                          <div class="count-set fr tc flex">
                            <a class="sub" @click="decrease(item.id, item.num)">
                            <span class="iconfont icon-jian"></span>
                            </a>
                            <div class="sub">
                              <input type="number" v-model="carts.items[shopindex].products[pk].num" class="buy-couts"/>
                            </div>
                            <!-- -->
                            <a class="sub" @click="increase(item.id, item.num)">
                            <span class="iconfont icon-jia"></span>
                            </a>
                          </div>
                        </div>
                    </div>
                  </div>
                </div>
            </van-checkbox-group>
          </div>
        </div>
    </van-checkbox-group>
      <!-- button v-if="!show_all_choise" class="cart-favorite-btn" @click="move_to_favor">移到收藏夹</button>
            <button v-if="!show_all_choise" class="cart-del-btn" @click="bind_delete_cart">删除</button> -->
    <van-submit-bar :price="carts.total" button-text="结算" @submit="confirmOrder">
        <van-checkbox v-model="all_is_checked" @change="all_checkboxChange">全选</van-checkbox>
        <span slot="tip">
          不含运费
        </span>
    </van-submit-bar>
  </div>
</template>
<script>
import Vue from 'vue'
import { Checkbox, CheckboxGroup, SubmitBar, NavBar } from 'vant';

Vue.use(Checkbox).use(CheckboxGroup).use(NavBar);
Vue.use(SubmitBar);
export default {

  data() {
    return {
      selected_products: [],
      selected_shop: [],
      checked: false,
      show_delete: false,
      finishProperty: false,

      canEdit: !1,
      hidden: !0,
      noMoreHidden: !0,
      carts: {
        items: [],
        total: 0
      },
      animation: '',

      cart_list: [],
      all_g_number: 0,
      all_g_price: 0,
      all_g_yunfei: 0,
      this_check_val: [],
      all_is_checked: false,
      btn_mall_sure_disabled: false,
      glo_is_load: true,
      prompt: {
        hidden: !0,
        icon: 'icon-cart',
        title: '这里还是空的呢',
        div: '',
      },
      showModalStatus: 0,

      show_all_choise: 1,
      current_finsh: 0,
      text: '编辑'
    }
  },

  created() {
    console.log(this.selected_shop, 'selected_shop')
    this.getCarts()
    // this.setData({ all_is_checked: false, 'carts.total': 0 })
  },
  methods: {


    //选择商品属性
    showDeleteChoice() {
      console.log('完成')
      this.show_all_choise = 1
    },
    showAllChoice() {

      this.show_all_choise = 0
    },

    showEdit() {
      if (!this.show_all_choise) {
        this.show_all_choise = 1 
        this.text            = '编辑'
      } else {
        this.show_all_choise = 0
        this.text            = '完成'
      }
    }, 

    back() {
      this.$router.back()
    },

    showProperty(e) {
      let id = e.currentTarget.dataset.id

      this.current_finsh = id

      var current_finsh = this.current_finsh
      console.log(current_finsh)
    },
    //选择商品属性  end


    showProduct(id) {
      this.$router.push({ path: '/shop/detail', query: { id: id } })

    },



    setModalStatus: function(status) {
      console.log("设置显示状态，1显示0不显示", e.currentTarget.dataset.status);
      var animation = wx.createAnimation({
        duration: 200,
        timingFunction: "linear",
        delay: 0
      })
      this.animation = animation
      animation.translateY(300).step()
      this.animationData = animation.export()
      if (status == 1) {
        this.showModalStatus = true
      }
      let that = this
      setTimeout(function() {
        animation.translateY(0).step()
        this.animationData = animation
        if (status == 0) {
          this.showModalStatus = false
        }
      }.bind(this), 200)
    },



    showShop(e) {
      let id = e.currentTarget.dataset.id
      this.util.navigateTo('/pages/shop/list/index', { shopid: id })
    },


    getCarts() {

      this.all_is_checked = false
      this.carts.items = []
      this.loading = !1
      this.prompt.hidden = !0


      this.HttpService.getCarts()
        .then(data => {
          this.loading = !0
          let products = []


          data.data.multi_list.forEach(n => {
            console.log(n)
            products = products.concat(n.products)
          })

          this.carts.items = data.data.multi_list
          this.products = products
          this.carts.total = 0
          this.prompt.hidden = !0
          this.loading = !0
          if (!data.data.multi_list.length) {
            this.prompt.hidden = !1
          }

          
        })
    },

    navigateTo(e) {
      console.log(e)
      this.util.navigateTo('/pages/detail/index', {
        id: e.currentTarget.dataset.id
      })
    },
    confirmOrder() {
      let shops     = []
     
      
      console.log(this.carts.items, this.this_check_val)

      let confirms    = this.carts.items

      confirms.forEach((n1, i1) => {
        let shop            = n1.shop
            shop.products   = []   
        for(let key in this.this_check_val) {
          let val   = this.this_check_val[key]

          n1.products.forEach((n2, i2) => {
            if(n2.id == val) {
              if(shop.id == n2.shop_id) {
                n2.price = (n2.price / n2.num).toFixed(2)
                shop.products.push(n2)
              }
            }
          })
        }
        if(shop.products.length) {
          shops.push(shop)
        }
      })

      this.util.removeStorageSync('carts')
      this.util.setStorageSync('carts', shops)
      this.$router.push('/shop/confirm')


        // console.log(confirmOrders)
        // return;
        // this.util.setStorageSync('confirmOrder', confirmOrders)
        // this.$router.push({path: '/order/confirm', query: {ids: ids}})
    },
    del(e) {
      const id = e.currentTarget.dataset.id
      console.log(id)

      this.util.showModal({
          title: '友情提示',
          content: '确定要删除这个宝贝吗？',
        })
        .then(data => {
          if (data.confirm == 1) {
            this.HttpService.delCartByUser({ id: id })
              .then(data => {
                console.log(data)
                if (data.status) {
                  this.getCarts()
                } else {
                  this.util.showModal({
                    title: '删除失败',
                    content: data.info,
                    showCancel: false
                  })
                }
              })
          }
        })
    },
    move_to_favor() {
      var that = this
      if (that.this_check_val.length == 0) {
        wx.showModal({
          title: '提示',
          content: '请选择要移入收藏夹的商品',
          showCancel: false,
        })
        return false;
      }

      this.util.showModal({
        title: '确认要移入收藏夹吗?',
        content: "同时将从购物车中删除",
      }).then(res => {
        if (res.confirm == true) {
          console.log(this.this_check_val)
          let check_val = this.this_check_val
          let carts = this.products
          let product_id = []
          carts.forEach(n => {
            console.log(n.id)
            check_val.forEach(val => {
              console.log(val)
              if (n.id == val)
                product_id.push(n.product_id)
            })
          })
          console.log(product_id)
          if (!product_id.length)
            return
          this.HttpService.favor({ id: product_id.join(',') }).then(data => {

            if (data.status) {
              this.HttpService.delCartByUser({ id: that.this_check_val.join(',') }).then(data => {
                if (data.status) {
                  this.getCarts()
                } else
                  this.util.showModal({
                    title: '删除失败',
                    content: data.info,
                    showCancel: false
                  })
              })
            } else
              this.util.showModal({
                title: '移入失败',
                content: data.info,
                showCancel: false
              })
          })

        }
      })
    },
    //删除购物车
    bind_delete_cart: function() {
      var that = this
      if (that.this_check_val.length == 0) {
        wx.showModal({
          title: '提示',
          content: '请选择要删除的商品',
          showCancel: false,
        })
        return false;
      }

      this.util.showModal({
        title: '提示',
        content: "确认要删除已购商品吗?",
      }).then(res => {
        if (res.confirm == true) {
          console.log(this.this_check_val)
          this.HttpService.delCartByUser({ id: that.this_check_val.join(',') }).then(data => {
            if (data.status) {
              this.getCarts()
            } else
              this.util.showModal({
                title: '删除失败',
                content: data.info,
                showCancel: false
              })
          })

        }
      })

    },
    clear() {
      this.util.showModal({
          title: '友情提示',
          content: '确定要清空购物车吗？',
        })
        .then(data => {
          if (data.confirm == 1) {
            this.HttpService.clearCartByUser()
              .then(data => {
                console.log(data)
                if (data.meta.code == 0) {
                  this.getCarts()
                }
              })
          }
        })
    },
    putCartByUser(id, params) {
      return this.HttpService.putCartByUser(id, params)
    },
    calTotal() {
      console.log('caltotal')
      let carts = this.carts.items
      let total = 0
      carts.forEach(n => {
        n.products.forEach(p => {
          if (p.is_checked)
            total += parseInt(p.num) * parseFloat(p.true_price)
        })
      })
      this.carts.total = total * 100

    },
    decrease(id, num) {
      num = parseInt(num)
      if (num == 1) {
        this.del(e)
        return
      }
      this.putCartByUser(id, {
        id: id,
        num: num - 1,
        type: 'minus'
      }).then(res => {
        if (res.status) {
          let carts = this.carts.items
          carts.forEach(c => {
            c.products.forEach(p => {
              if (p.id == id) {
                p.num = num - 1
              }
            })
          })
          this.carts.items = carts

          this.calTotal()
        } else
          this.util.showModal({
            title: res.info || '操作失败'
          })
      })
    },
    numchange(num) {
      if (num == 0) {
        this.del()
        return
      }
      this.putCartByUser(id, {
        id: id,
        num: num,
        type: 'change'
      }).then(res => {
        if (res.status) {
          let carts = this.carts.items
          carts.forEach(c => {
            c.products.forEach(p => {
              if (p.id == id) {
                p.num = num
              }
            })
          })
          this.setData({
            'carts.items': carts
          })
          this.calTotal()
        } else {
          this.util.showModal({
            title: res.info || '操作失败'
          }).then(data => {
            let carts = this.carts.items

            this.setData({
              'carts.items': carts
            })
          })

        }
        // this.calTotal()

      })
    },
    increase(id, num) {
      num = parseInt(num)
      this.putCartByUser(id, {
        id: id,
        num: num + 1,
        type: 'increase'
      }).then(res => {
        if (res.status) {
          let carts = this.carts.items
          carts.forEach(c => {
            c.products.forEach(p => {
              if (p.id == id) {
                p.num = num + 1
              }
            })
          })
          this.carts.items = carts

        } else
          this.$vux.confirm.show({
            title: res.info || '操作失败'
          })
      })
    },


    //全选
    all_checkboxChange: function(isallcheck) {
        

      return;
      let that = this
      var datas = that.carts.items
      var check_val = []
      for (var i = 0; i < datas.length; i++) {
        datas[i].is_checked = isallcheck
        for (var j = 0; j < datas[i].products.length; j++) {
          if (datas[i].products[j].stock > 0)
            datas[i].products[j].is_checked = isallcheck
          if (isallcheck && datas[i].products[j].stock > 0) {
            check_val.push(datas[i].products[j].id)
          }
        }
      }

      this.carts.items = datas
      this.this_check_val = check_val

    },
    //单选
    single_checkboxChange: function(check_val) {

      var that = this
      console.log(check_val)
      var c_length = check_val.length
      var g_length = this.carts.items.length
      let carts = this.carts.items
      let total = 0
      let all_is_checked = false
      if (c_length >= g_length) {
        all_is_checked = true
      }
      let all_check_val = []
      carts.forEach(n => {
        if (n.is_checked == true) {
          let flag = false
          check_val.forEach(c => {
            if (c == n.shop.id)
              flag = true
          })
          n.is_checked = flag
          if (!flag)
            n.products.forEach(p => {
              p.is_checked = flag
            })
        }
        check_val.forEach(c => {
          console.log(c)
          if (c == n.shop.id) {
            n.is_checked = true
            n.products.forEach(p => {
              p.is_checked = true
              all_check_val.push(p.id)
            })
          }
        })
      })

      this.carts.items = carts
      this.all_is_checked = all_is_checked
      this.this_check_val = all_check_val

    },
    product_change(check_val) {

      /* 不知道为什么 */
      this.carts.items.forEach((item, index) => {
        item.is_checked = false
      })  

      var c_length = check_val.length
      let cart = this.carts.items
      let topFlag = true
      let total = 0 
      console.log(total)
      let all_is_checked = false
      let selected_shop = this.selected_shop
      cart.forEach(n => {
      let flag = true

          n.products.forEach(p => {
            if (check_val.indexOf(p.id) == -1 ) {
              flag = false
              topFlag = false
            }else{
              total += parseFloat(p.true_price) * parseInt(p.num)
            }
          })

        if (flag && selected_shop.indexOf(n.shop.id)  == -1) {
            n.is_checked = true
         
            selected_shop.push(n.shop.id)
        }
      })
      if (topFlag)
        all_is_checked = true
      total = parseFloat(total.toFixed(2))*100
      // console.log(total)
      // console.log(parseFloat(total))
      this.carts.items = cart,
      this.carts.total = (total)
      this.all_is_checked = all_is_checked
      this.selected_shop = selected_shop
        // this.this_check_val = check_val

    }
  }
}

</script>

<style scoped>
  @import './cart.css';
</style>